import pygame
pygame.init()
pygame.key.set_repeat(640,480)
import random
import os


def main():
        txtcolor = (250,250,250)
        tela = pygame.display.set_mode((640,480))
        tela.fill((255,255,255))
        erase = pygame.Rect(0,0,120,85)
        mafont0 = pygame.font.SysFont('calibri',15) ; mafont1 = pygame.font.SysFont('calibri',56) ; mafont2 = pygame.font.SysFont('calibri',20); mafont3 = pygame.font.SysFont('calibri',20)
        tela.blit(pygame.image.load('./Imagens/fundo2.jpg'),(0,0))
        mask = pygame.image.load('./Imagens/mask.png')

        matriz = (((0,0,0,15),(4,4,4,4),(0,0,0,15),(2,2,2,2)),
                 ((0,0,6,6),(0,0,6,6),(0,0,6,6),(0,0,6,6)),
                 ((0,0,2,14),(0,4,4,6),(0,0,7,4),(0,6,2,2)),
                 ((0,0,7,1),(0,2,2,6),(0,0,4,7),(0,6,4,4)),
                 ((0,0,6,12),(0,4,6,2),(0,0,3,6),(0,4,6,2)),
                 ((0,0,12,6),(0,2,6,4),(0,0,6,3),(0,2,6,4)),
                 ((0,0,2,7),(0,4,6,4),(0,0,7,2),(0,2,6,2)))
        class Objet:
                def __init__(self,matriz,index,couleur):
                        self.x = 4 ; self.y = 0
                        self.rect = pygame.Rect(80,0,80,80)
                        self.objet = matriz
                        self.index = index
                        self.couleur = couleur
                        self.make_image()
                        pygame.time.set_timer(pygame.USEREVENT,speed)
                def make_image(self):
                        surface = pygame.Surface((80,80)).convert_alpha()
                        surface.fill((0,0,0,0))
                        for i,x in enumerate(self.objet[self.index]):
                                if x:
                                        for j,y in enumerate(bin(x)[2:].zfill(4)):
                                                if y=='1':
                                                        surface.fill(self.couleur,(j*20,i*20,20,20))
                                                        surface.blit(mask,(j*20,i*20))
                        self.image = surface

                def draw(self):
                        erase.topleft = (self.rect.x-20,self.rect.y-5)
                        tela.blit(bg,erase.topleft,erase)
                        tela.blit(self.image,self.rect.topleft)
                        tela.blit(bg,(20,0),(20,0,200,80))
                        pygame.display.update((erase,(20,0,200,80)))
                def update(self):
                        def shift(direction):
                                ref = [int(i*2**(8-self.x-direction)) for i in self.objet[self.index]]
                                if not any(a&b for a,b in zip(ref,grid[self.y:])):
                                        self.x += direction ; self.rect.x += direction*20 ; self.draw()
                        def down():
                                if self.rect.y%20==0:
                                        ref = [int(i*2**(8-self.x)) for i in self.objet[self.index]]
                                        if not any(a&b for a,b in zip(ref,grid[self.y+1:])):
                                                self.y += 1 ; self.rect.y += 2 ; self.draw()
                                                return 1
                                        else: return 0
                                else :
                                        self.rect.y += 2
                                        self.draw()
                                        return 1
                        def rotate():
                                ref = [int(i*2**(8-self.x)) for i in self.objet[(self.index+1)%4]]
                                if not any(a&b for a,b in zip(ref,grid[self.y:])):
                                        self.index = (self.index+1)%4
                                        self.make_image()
                                        self.draw()
                        while True:
                                e =  pygame.event.wait().type
                                if e == pygame.USEREVENT:
                                        if not down() : break
                                elif e == pygame.KEYDOWN:
                                        keys = pygame.key.get_pressed()
                                        if keys[pygame.K_LEFT]:shift(-1)
                                        elif keys[pygame.K_RIGHT]:shift(1)
                                        elif keys[pygame.K_UP]:rotate()
                                        elif keys[pygame.K_ESCAPE]:import menu
                                        elif keys[pygame.K_p]:
                                                tela.blit(mafont3.render('PAUSE',1,txtcolor),(30,200))
                                                tela.blit(mafont3.render('Pressione uma tecla para iniciar',1,txtcolor),(30,225))
                                                pygame.display.flip()
                                                while pygame.event.wait().type != pygame.KEYDOWN : pass
                                                tela.blit(bg,(0,0))
                                                tela.blit(self.image,self.rect.topleft)
                                                tela.blit(bg,(20,0),(20,0,200,80))
                                                pygame.display.flip()
                                        elif keys[pygame.K_DOWN]:
                                                self.rect.y = int(self.rect.y)
                                                while down() and pygame.event.poll().type != pygame.KEYUP: pygame.time.wait(2)
                                elif e == pygame.QUIT:
                                        pygame.event.post(pygame.event.Event(pygame.QUIT))
                                        pygame.event.post(pygame.event.Event(pygame.QUIT))
                                        break
                        
        def grid_update(obj):
                global bg,speed,score,speedx
                sc = 0
                ref = [int(i*2**(8-obj.x)) for i in obj.objet[obj.index]]
                for a,i in enumerate(ref):
                        grid[obj.y+a]=grid[obj.y+a]|i
                        if grid[obj.y+a]==4095:
                                sc += 100
                                del(grid[obj.y+a])
                                grid.insert(0,2049)
                                tela.blit(tela,(20,100),(20,80,200,(obj.y+a)*20-80))
                score += sc ; speedx += sc*0.000225 ; speedx -= 0.1 ; speed = int(speedx)
                if speed == 0:
                        tela.blit(mafont3.render('Velocidade Max',1,txtcolor),(30,150))
                        tela.blit(mafont2.render('bug nao corrigido ainda',1,txtcolor),(30,175))
                        tela.blit(mafont3.render('ENTER para recomecar o jogo',1,txtcolor),(27,230))
                        pygame.event.clear()
                        pygame.event.post(pygame.event.Event(pygame.QUIT))
                tela.fill((255,255,255),(236,239,164,15))
                tela.blit(mafont0.render(str(50-speed),1,(25,50,250)),(236,239))
                tela.fill((255,255,255),(236,289,164,15))
                tela.blit(mafont0.render(str(score),1,(25,50,250)),(236,289))
                pygame.display.flip()
                bg = tela.copy()

        def play():
                global bg,grid,speed,score,speedx
                speedx = 50 ; speed = 50 ; score = 0
                tela.fill((0,0,0),(20,80,200,400))
                grid = [2049]*24+[4095]
                tela.fill((255,255,255),(236,239,164,15)) ; tela.fill((255,255,255),(236,289,164,15)) ; tela.fill((0,0,0),(221,120,80,80))
                tela.blit(mafont0.render(str(1),1,(25,50,250)),(236,239)) ; tela.blit(mafont0.render(str(0),1,(25,50,250)),(236,289))
                next = Objet(matriz[random.randint(0,5)],random.randint(0,3),(random.randint(100,255),random.randint(0,255),random.randint(0,255)))
                tela.blit(next.image,(221,120))
                tela.blit(mafont3.render('Pressione uma tecla para iniciar',1,txtcolor),(30,200))
                pygame.display.flip()
                tela.fill((0,0,0),(20,80,200,400))
                while True:
                	if pygame.event.wait().type == pygame.QUIT:return
                	elif pygame.event.wait().type == pygame.KEYDOWN:break
                while pygame.event.wait().type != pygame.QUIT:
                        truc = next
                        next = Objet(matriz[random.randint(0,6)],random.randint(0,3),(random.randint(200,255),random.randint(100,255),random.randint(0,255)))
                        tela.fill((0,0,0),(221,120,80,80))
                        tela.blit(next.image,(221,120))
                        pygame.display.flip()
                        bg = tela.copy()
                        truc.update()
                        if truc.y==0 :
                                tela.blit(mafont3.render('PERDEU !',1,txtcolor),(30,200))
                                tela.blit(mafont3.render('ENTER para recomecar o jogo',1,txtcolor),(27,230))
                                pygame.display.flip()
                                break
                        grid_update(truc)

        play()
        while pygame.event.wait().type != pygame.QUIT:
                if pygame.key.get_pressed()[pygame.K_RETURN]: play()
                if pygame.key.get_pressed()[pygame.K_ESCAPE]: return
if __name__ == "__main__": main()
